package com.superman.mvpframe.client.ajax;

import com.google.gwt.http.client.Response;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.superman.mvpframe.client.event.LoginEvent;
import com.superman.mvpframe.client.event.ToastEvent;
import com.superman.mvpframe.client.gin.XGinjector;
import com.superman.mvpframe.client.utils.LogUtils;

/**
 * Ajax 异步回调基础类
 * 
 * @author superman
 * @version 2018年7月12日下午3:33:42
 */
public abstract class PostManAsyncCallBack implements IPostManAsyncCallBack {
	/**
	 * 业务处理失败
	 * 
	 * @author superman
	 * @version 2018年7月12日 下午4:30:02
	 * @param statusCode
	 */
	public abstract void onBusinessError(String statusCode);

	/**
	 * 业务处理成功
	 * 
	 * @author superman
	 * @version 2018年7月12日 下午4:30:00
	 * @param response
	 */
	public abstract void onBusinessOK(String response);

	@Override
	public void onHttpError(String fullPostUrl, int statusCode) {
		LogUtils.logPostReceived(fullPostUrl, statusCode, "");
		switch (statusCode) {
			case Response.SC_FORBIDDEN:
				// session过期.重新登录
				XGinjector.INSTANCE.getEventBus().fireEvent(new LoginEvent());
				break;
			case Response.SC_UNAUTHORIZED:
				// 签名错误
				XGinjector.INSTANCE.getEventBus().fireEvent(new ToastEvent("网络请求失败,请重试"));
				break;
			case Response.SC_BAD_REQUEST:
				// 未带上签名
				XGinjector.INSTANCE.getEventBus().fireEvent(new ToastEvent("网络请求失败,请重试"));
				break;
			case -1:
				// 超时
				XGinjector.INSTANCE.getEventBus().fireEvent(new ToastEvent("啊哦,你的网络好像不太给力哦"));
				break;
			default:
				// 其他
				XGinjector.INSTANCE.getEventBus().fireEvent(new ToastEvent("啊哦,你的网络好像不太给力哦"));
				break;
		}
	}

	@Override
	public void onHttpOK(String fullPostUrl, String response) {
		LogUtils.logPostReceived(fullPostUrl, 200, response);
		JSONObject jo = JSONParser.parseStrict(response).isObject();
		String rspcd = jo.get("rspcd").isString().stringValue();
		String rspmsg = jo.get("rspmsg").isString().stringValue();
		if (rspcd.equals("000000") && rspmsg.equals("succeed")) {
			onBusinessOK(response);
		} else {
			String toastRspMsg = "";
			switch (rspcd) {
				case BusinessErrorConstants.INTERNAL_ERROR:
					toastRspMsg = "服务器开小差了,请重试";
					break;
				case BusinessErrorConstants.MISSING_PARAMS:
					toastRspMsg = "程序出错,请重试";
					break;
				default:
					toastRspMsg = rspmsg;
					break;
			}

			XGinjector.INSTANCE.getEventBus().fireEvent(new ToastEvent(toastRspMsg));
			onBusinessError(rspcd);
		}
	}
}
